/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xui_lib.component.edittext;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

/**
 * PwdTextView
 *
 * @since 2021-03-24
 */
public class PwdTextView extends Text {
    private static final int TWO = 2;
    private float mRadius;
    private boolean isHasPassword;
    private Paint mPaint;

    /**
     * 构造函数
     *
     * @param context
     */
    public PwdTextView(Context context) {
        this(context, null);
    }

    /**
     * 构造函数
     *
     * @param context
     * @param attrSet
     */
    public PwdTextView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    /**
     * 构造函数
     *
     * @param context
     * @param attrSet
     * @param styleName
     */
    public PwdTextView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint(); // 画一个黑色的圆
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        mPaint.setTextAlign(TextAlignment.VERTICAL_CENTER);
        addDrawTask(new DrawTask() {
            @Override
            public void onDraw(Component component, Canvas canvas) {
                if (isHasPassword) {
                    canvas.drawCircle(getWidth() >> 1, getHeight() >> 1, mRadius, mPaint);
                }
            }
        });
    }

    /**
     * 清除密码
     */
    public void clearPassword() {
        isHasPassword = false;
        invalidate();
    }

    /**
     * 绘制密码
     *
     * @param radius
     */
    public void drawPassword(float radius) {
        isHasPassword = true;
        if (radius == 0) {
            mRadius = getWidth() >> TWO; // 除以4
        } else {
            mRadius = radius;
        }
        invalidate();
    }
}
